<template>
  <div>
    <Tooltip content="系统的/etc/hosts文件"> 当前系统的host信息 </Tooltip>
    <Button shape="circle" type="info" @click="add()">新增</Button>
    <Poptip
      trigger="hover"
      title="权限"
      content="需要授权hosts文件的写权限，尝试命令: sudo chmod 666 /etc/hosts"
    >
      <Button shape="circle" type="success" @click="save()">保存</Button>
    </Poptip>
    <Table
      :columns="tableColumm"
      :data="tableData"
      :border="true"
      :stripe="true"
      ref="selection"
    ></Table>
    <Modal v-model="commandModal" title="新增配置" @on-ok="checkadd">
      <Form :model="addItem" :label-width="80">
        <FormItem label="IP地址">
          <Input v-model="addItem.ip" placeholder="ip地址"></Input>
        </FormItem>
        <FormItem label="主机名">
          <Input v-model="addItem.name" placeholder="主机名"></Input>
        </FormItem>
        <FormItem label="是否启用">
          <i-switch v-model="addItem.switch" size="large">
            <span slot="open">启用</span>
            <span slot="close">失效</span>
          </i-switch>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import os from "os";
import fs from "fs";
import * as CONSTANT from "../../lib/constants";
import common from "../../lib/common";
export default {
  data() {
    return {
      commandModal: false,
      disabled: true,
      tableColumm: [
        {
          title: "#",
          key: "index",
          width: 60,
          resizable: true,
        },
        {
          title: "ip",
          key: "ip",
          resizable: true,
        },
        {
          title: "主机名",
          key: "name",
          resizable: true,
        },
        {
          title: "是否生效",
          width: 100,
          render: (h, params) => {
            return h("div", [
              h("i-switch", {
                //数据库1是已处理，0是未处理
                props: {
                  type: "primary",
                  value: params.row.switch, //控制开关的打开或关闭状态，官网文档属性是value
                  disabled: params.row.switch == null ? true : false, //如果是null的 就是无法解析的数据
                },
                style: {
                  marginRight: "5px",
                },
                on: {
                  "on-change": (value) => {
                    //触发事件是on-change,用双引号括起来，
                    //参数value是回调值，并没有使用到
                    this.switch(params.index, value); //params.index是拿到table的行序列，可以取到对应的表格值
                  },
                },
              }),
            ]);
          },
        },
        {
          title: "操作",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                    disabled: params.row.switch == null ? true : false, //如果是null的 就是无法解析的数据
                  },
                  style: {
                    marginRight: "5px",
                  },
                  on: {
                    click: () => {
                      this.change(params.index);
                    },
                  },
                },
                "修改"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small",
                    
                  },
                  on: {
                    click: () => {
                      this.remove(params.index);
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
          width: 160,
        },
      ],
      tableData: [],
      addItem: {
        index: "0",
        ip: "",
        name: "",
        switch: true,
      },
    };
  },
  methods: {
    //index 下标 value  true/false
    switch(index, value) {
      this.tableData[index].switch = value;
    },
    transferHost2List(data) {
      let list = data.split(CONSTANT.EOL);
      for (let i = 0; i < list.length; i++) {
        //去掉多余的空格 防止出现异常
        let line = common.trimSpace(list[i]);
        //判断长度大于2的情况 如果第一个是# 也是正常的
        let transferd = {
          index: i + 1,
        };

        //判断解出来的host
        if (line.length > 2) {
          if (line.length === 3 && line[0].indexOf("#") !== -1) {
            transferd.ip = line[1];
            transferd.name = line[2];
            transferd.switch = false;
          } else {
            transferd.ip = list[i];
            transferd.name = CONSTANT.HOSTS_NOT_PARSE;
            transferd.switch = null;
          }
        } else if (line.length === 2) {
          if (line[0].indexOf("#") !== -1) {
            line[0] = line[0].slice(1);
            transferd.ip = line[0];
            transferd.name = line[1];
            transferd.switch = false;
          } else {
            transferd.ip = line[0];
            transferd.name = line[1];
            transferd.switch = true;
          }
        } else {
          transferd.ip = list[i];
          transferd.name = CONSTANT.HOSTS_NOT_PARSE;
          transferd.switch = null;
        }
        this.tableData.push(transferd);
      }
    },
    //新增host配置
    add() {
      this.commandModal = true;
      this.addItem = {
        switch: false,
      };
    },
    checkadd() {
      console.log("this.addItem :>> ", this.addItem);
      this.addItem.index = this.tableData.length + 1;
      this.tableData.push(this.addItem);
    },
    //保存host配置
    save() {
      let text = "";
      for (let i = 0; i < this.tableData.length; i++) {
        let data = this.tableData[i];
        if (data.name == CONSTANT.HOSTS_NOT_PARSE) {
          text += data.ip;
        } else {
          if (data.switch == false) {
            text += "#";
          }
          text += data.ip + " " + data.name;
        }

        //如果不是文件尾 增加换行符
        if (i != this.tableData.length - 1) {
          text += CONSTANT.EOL;
        }
      }
      try {
        fs.writeFileSync(CONSTANT.HOSTS, text);
        this.$Message.success("保存成功!");
      } catch (error) {
        error = error.toString();
        if (error.indexOf("permission") != -1) {
          this.$Modal.error({
            title: "处理失败",
            content: "权限不足 尝试命令: sudo chmod 666 /etc/hosts",
          });
        } else {
          this.$Message.error(error);
        }
      }
    },
    loadHost() {
      this.tableData = [];
      let platform = os.platform();
      if (platform != "darwin" && platform != "linux") {
        this.$Message.error("暂时只支持Linux和MacOS系统");
        return;
      }
      try {
        let res = fs.readFileSync(CONSTANT.HOSTS);

        res = res.toString();
        this.transferHost2List(res);
      } catch (error) {
        error = error.toString();
        if (error.indexOf("permission") != -1) {
          this.$Modal.error({
            title: "处理失败",
            content: "权限不足 尝试命令: sudo chmod 666 /etc/hosts",
          });
        } else {
          this.$Message.error("读取host报错->", error);
        }
      }
    },
    remove(index) {
      console.log('index :>> ', index);
      this.tableData.splice(index,1);
      // this.loadHost();

    },
    change(index) {

    }
  },
  created() {
    this.loadHost();
  },
};
</script>

<style>
</style>